#include <QHostAddress>
#include <QNetworkInterface>

#include "systeminfo.h"

SystemInfo::SystemInfo()
{

}

QString SystemInfo::getIPAddress()
{
    QString ipAddr;
    for (const QHostAddress &address: QNetworkInterface::allAddresses()) {
        if (address.protocol() == QAbstractSocket::IPv4Protocol && address != QHostAddress(QHostAddress::LocalHost)) {
            if (address.toString().contains("169."))
                continue;
            ipAddr = address.toString();
            break;
        }
    }
    return ipAddr;
}

QList<QPair<QString,QString> > SystemInfo::systemInfo()
{
    QList<QPair<QString, QString>> systemInfo;
    systemInfo
#ifdef Q_OS_MACOS
    << QPair<QString, QString>(u8"操作系统：", QString(u8"Mac OS X %1").arg(QSysInfo::productVersion()));
#else
    << QPair<QString, QString>(u8"操作系统：", QString(u8"Windows %1").arg(QSysInfo::productVersion()));
#endif

    std::string cpuBrand;

    QList<uint> inputs {0x80000002,0x80000003,0x80000004};

    for (uint input: inputs) {
        CPUID cpuID(input);

        cpuBrand += std::string((const char *)&cpuID.EAX(), 4);
        cpuBrand += std::string((const char *)&cpuID.EBX(), 4);
        cpuBrand += std::string((const char *)&cpuID.ECX(), 4);
        cpuBrand += std::string((const char *)&cpuID.EDX(), 4);
    }

    systemInfo << QPair<QString, QString>(u8"处理器(CPU)：", QString::fromStdString(cpuBrand));
    return systemInfo;
}

QString SystemInfo::getCPUInfo()
{
    return (SystemInfo::systemInfo().end()-1)->second;
}

QString SystemInfo::getOSInfo()
{
    return SystemInfo::systemInfo().begin()->second;
}

QString SystemInfo::getMACAdress() {
    QNetworkInterface thisNet;      //所要使用的网卡
    QList<QNetworkInterface> NetList = QNetworkInterface::allInterfaces();//获取所有网卡信息
    int NetCount = NetList.count();         //统计网卡个数
    for(int Neti = 0;Neti < NetCount; Neti++){   //遍历所有网卡
        thisNet = NetList[Neti];    //将该网卡置为当前网卡
        if(thisNet.isValid() && thisNet.flags().testFlag(QNetworkInterface::IsUp) && thisNet.flags().testFlag(QNetworkInterface::IsRunning)){    //判断该网卡是否是合法
            break;
        }
    }
    return thisNet.hardwareAddress();   //获取该网卡的MAC
}
